<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElCard, ElTable, ElTableColumn, ElMessage } from 'element-plus'


import { listUser, getUser, delUser, addUser, updateUser } from "@/api/User";
import { listDepartment } from "@/api/department";
import {Delete, Edit, Plus, Refresh, Search} from "@element-plus/icons-vue";
// 弹框状态
const formVisible = ref(false)
const title = ref('')

// 用户表单数据
const userForm = ref( { 
    username: '',
    parentId: null,
    realName:  null,
    avatar: null,
    gender: null,
    email: null,
    mobile: null,
    password: null,
    userCode: null
  })

// 用户树形数据
const parentDepartments = ref([])

// 用户列表数据
const userList = ref([])

// 是否为编辑状态
const isEditMode = ref(false)

// 当前编辑的用户ID
const currentLocationId = ref(null)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名称', trigger: 'blur' }
  ]
}
const genderMap = {
  1: '男',
  2: '女',
  3: '其他'
}
// 获取用户列表数据
const listUserData = () => {
  listUser().then(res => {
    if (res.code === 200) {
      userList.value = res.data.map(user => ({
        ...user,
        genderName: genderMap[user?.gender] || '未知'
      }))
    }
  })
}

// 提交用户表单
const handleSubmit = () => {
  const departments = userForm?.value?.parentId?.map(number => ({id: number}));
  // 检查用户名称是否为空
  if (!userForm.value.username) {
    ElMessage.warning('请输入账号');
    return;
  }

  const apiMethod = isEditMode.value 
    ? updateUser 
    : addUser;
  
  const requestData = {
    id: currentLocationId.value,
    username: userForm.value.username,
    mobile: userForm.value.mobile,
    departments: departments,
    realName:  userForm.value.realName,
    avatar: userForm.value.avatar,
    gender: userForm.value.gender,
    email: userForm.value.email,
    password: userForm.value.password,
    userCode: userForm.value.userCode
  };

  apiMethod(requestData).then(res => {
    if (res.code === 200) {
      ElMessage.success(`${isEditMode.value ? '更新' : '新增'}成功`);
      formVisible.value = false;
      resetForm();
      listDepartmentData();
      listUserData()
    }
  });
}

// 重置表单
const resetForm = () => {
  isEditMode.value = false;
  currentLocationId.value = null;
  userForm.value = { 
    username: '',
    parentId: null,
    realName:  null,
    avatar: null,
    gender: null,
    email: null,
    mobile: null,
    userCode: null
  };
}

// 新增用户
const addUserData = () => {
  isEditMode.value = false;
  formVisible.value = true;
  resetForm();
  title.value = '新增用户'
}

// 获取用户树形结构
const listDepartmentData = () => {
  listDepartment().then(res => {
    if (res.code === 200) {
      parentDepartments.value = res.data
    }
  })
}

// 删除用户
const delUserData = (row) => {
  console.log(row, "删除")
  delUser(row.id).then(res => {
    if (res.code === 200) {
      ElMessage.success('删除成功')
      listUserData()
    }
  }).catch(err => {
    ElMessage.error('删除失败')
  })
}

// 编辑用户
const editUserData = (row) => {
  title.value = '编辑用户'
  // 根据id获取用户详情
  getUser(row.id).then(res => {
    if (res.code === 200) {
      isEditMode.value = true;
      currentLocationId.value = row.id;

      const parentId = res.data.departments.map(item => (item.id + ''));
      console.log("editUserData", parentId);
      userForm.value = {
        username: res.data.username,
        realName: res.data.realName,
        avatar: res.data.avatar,
        gender: res.data.gender,
        email: res.data.email,
        mobile: res.data.mobile,
        parentId: parentId,
        userCode: res.data.userCode
      }
      formVisible.value = true
    }
  })
}


// 搜索框绑定的用户名称
const queryForm = ref({
  username: ''
})

// 按用户名称搜索的方法
const handleSearch = () => {
  // 判断是否为空
  if (!queryForm.value.username) {
    ElMessage.warning('请输入用户名称');
    return;
  }
  const params = {
    username: queryForm.value.username
  }
  listUser(params).then(res => {
    if (res.code === 200) {
      userList.value = res.data
    }
  })
}
enum ImgType {
  JPG = 'image/jpg',
  JPEG = 'image/jpeg',
  PNG = 'image/png',
  GIF = 'image/gif',
  BMP = 'image/bmp',
  WEBP = 'image/webp',
  SVG = 'image/svg',
  UNKNOWN = 'image/unknown'
}
const imgUrl = ref<string>("");
const beforeUpload = (file: any) => {
  if (!Object.values(ImgType).includes(file["type"])) {
    ElMessage.error('请上传图片');
    return false;
  }
  return true;
}
const uploadImg = (response: any, uploadFile: UploadFile) => {
  console.log(response)
  imgUrl.value = response.data;
  userForm.value.avatar = response.data;
  // assetData.value.pic = response.data
}
// 重置搜索条件
const handleReset = () => {
  queryForm.value.username = ''
  listUserData()
}

onMounted(() => {
  listDepartmentData()
  listUserData()
})
</script>

<template>
  <!-- 新增搜索框 -->
  <el-form :inline="true" :model="queryForm" class="demo-form-inline" style="margin-top: 10px;">
    <el-form-item>
      <el-space>
        <el-input v-model="queryForm.username" placeholder="部门名称" clearable :prefix-icon="Search">
          <template #append>
            <el-button type="primary" :icon="Search" :style="$globalAttribute.primaryButton" @click="handleSearch">
              搜索
            </el-button>
          </template>
        </el-input>
        <el-button type="primary" :icon="Refresh" plain @click="handleReset">
          重置
        </el-button>
        <el-button plain type="primary" :icon="Plus" @click="addUserData">
          新增用户
        </el-button>
      </el-space>
    </el-form-item>
  </el-form>

  <el-dialog v-model="formVisible" :title="title" width="30%">
    <el-form :model="userForm" :rules="rules" label-width="100px">
      <el-form-item label="账号" prop="username" :rules="[{required:true,message:'请填写账号'}]">
        <el-input v-model="userForm.username" />
      </el-form-item>

      <el-form-item v-show="!isEditMode" label="密码" prop="password"
      :rules="[{required:true,message:'请填写密码'}]">
        <el-input v-model="userForm.password" type="password"/>
      </el-form-item>
      <el-form-item label="姓名" prop="realName" :rules="[{required:true,message:'请填写姓名'}]">
        <el-input v-model="userForm.realName" />
      </el-form-item>
      <el-form-item label="工号" prop="userCode" :rules="[{required:true,message:'请填写工号'}]">
        <el-input v-model="userForm.userCode" />
      </el-form-item>
      <el-form-item label="头像">
        <el-image style="width: 50px;height: 50px" v-if="imgUrl" :src="'http://localhost:8081/'+imgUrl"
                  fit="cover"></el-image>
        <el-upload
            action="http://localhost:8081/common/upload"
            :with-credentials="true"
            name="file"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="uploadImg"
        >
          <div class="uploadBtn">
            <el-icon class="iconfont icon-shangchuan"></el-icon>
          </div>
        </el-upload>
      </el-form-item>
      
      <!-- <el-form-item label="头像" prop="avatar">
        <el-input v-model="userForm.avatar" />
      </el-form-item> -->
      <!-- <el-form-item label="性别" prop="gender"> -->
        <!-- <el-input v-model="userForm.gender" /> -->
      <el-form-item label="性别"  prop="gender" :rules="[{required:true,message:'请选择性别'}]">
        <el-select
          v-model="userForm.gender"
          clearable
          placeholder="选择性别"
          style="width: 240px"
        >
          <el-option
            key="1"
            label="男"
            value="1"
          />
          
          <el-option
            key="2"
            label="女"
            value="2"
          />
          
          <el-option
            key="3"
            label="其他"
            value="3"
          />
        </el-select>

      <!-- </el-form-item> -->
      </el-form-item>
      <el-form-item label="邮箱地址" prop="email">
        <el-input v-model="userForm.email" />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input v-model="userForm.mobile" />
      </el-form-item>
      
      <el-form-item label="所属部门">

        <el-tree-select
            v-model="userForm.parentId" placeholder="请选择部门"
            :data="parentDepartments"
            node-key="id"
            :props="{label:'deptName',children:'children'}"
            check-strictly
            multiple
            :render-after-expand="false"
            style="width: 200px"
        ></el-tree-select>
      </el-form-item>
      <div class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-form>
  </el-dialog>
  <el-table :data="userList" height="80%">
    <el-table-column prop="username" label="账号" align="left"/>
    <el-table-column prop="realName" label="姓名" align="center"/>
    <el-table-column prop="userCode" label="工号" align="center"/>

    <!--    <el-table-column prop="avatar" label="头像URL" align="center"/>-->
    <el-table-column label="头像" width="120">
      <template #default="scope">
        <el-image :lazy="true" :src="'http://localhost:8081/'+scope.row.avatar"
                  :preview-src-list="['http://localhost:8081/'+scope.row.avatar]" :z-index="999999"
                  :preview-teleported="true" style="width: 40px;height:40px;"></el-image>
      </template>
    </el-table-column>
    <el-table-column prop="genderName" label="性别" align="center"/>
    <el-table-column prop="email" label="邮箱地址" align="center"/>
    <el-table-column prop="mobile" label="手机号码" align="center"/>
    <el-table-column label="操作" align="center" width="200">
      <template #default="scope">
        <el-space>
          <el-link type="primary" link :icon="Edit" @click="editUserData(scope.row)">编辑</el-link>
          <el-link type="danger" link :icon="Delete" @click="delUserData(scope.row)">删除</el-link>
        </el-space>
      </template>
    </el-table-column>
  </el-table>
</template>

<style scoped lang='less'>
.mb-4 {
  margin-bottom: 1rem;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

// 添加级联面板样式
:deep(.cascader-popper) {
  .el-cascader-node:not(.is-leaf) > .el-cascader-node__label {
    color: #409EFF;
    &::after {
      content: '（可选）';
      font-size: 12px;
      color: #999;
    }
  }
}
</style>